package com.lingxu.module.risk.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingxu.base.common.api.vo.Result;
import com.lingxu.module.collection.entity.ModelColumnInfo;
import com.lingxu.module.collection.mapper.ModelCategoryMapper;
import com.lingxu.module.collection.mapper.ReportMapper;
import com.lingxu.module.database.entity.TModel;
import com.lingxu.module.process.mapper.ModelMapper;
import com.lingxu.module.risk.entity.ModelRunQueryParams;
import com.lingxu.module.risk.entity.ModelRunVo;
import com.lingxu.module.risk.entity.TModelRunRecord;
import com.lingxu.module.risk.mapper.TModelRunRecordMapper;
import com.lingxu.module.risk.service.RiskService;
import com.lingxu.module.risk.vo.JsonFieldsVo;
import org.apache.shiro.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.*;
import java.util.*;
import java.util.Date;
import java.util.stream.Collectors;

@Service
public class RiskServiceImpl implements RiskService {

    @Resource
    private TModelRunRecordMapper tModelRunRecordMapper;

    @Resource
    private ReportMapper reportMapper;
    @Resource
    private ModelMapper tModelMapper;
    @Resource
    private ModelCategoryMapper modelCategoryMapper;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<ModelRunVo> queryModelRunList(ModelRunQueryParams query) {
        List<TModelRunRecord> list = tModelRunRecordMapper.selectList(
                new LambdaQueryWrapper<TModelRunRecord>()
                        .eq(StrUtil.isNotEmpty(query.getModelid()), TModelRunRecord::getModelid, query.getModelid())
                        .eq(StrUtil.isNotEmpty(query.getUserid()), TModelRunRecord::getUserid, query.getUserid())
                        .eq(TModelRunRecord::getRuntype, "01")
                        .eq(TModelRunRecord::getRunstatus, "01")
                        .eq(TModelRunRecord::getRunprocess, "5")
                        .like(StrUtil.isNotEmpty(query.getRemark()), TModelRunRecord::getRemark, query.getRemark())
                        .isNull(StrUtil.isEmpty(query.getCheckedStatus()), TModelRunRecord::getCheckedStatus)
                        .eq(StrUtil.isNotEmpty(query.getCheckedStatus()), TModelRunRecord::getCheckedStatus, query.getCheckedStatus())
                        .orderByDesc(TModelRunRecord::getEndtime)
        );
        return list.stream().map(e -> {
            ModelRunVo vo = new ModelRunVo();
            vo.setModelid(e.getModelid());
            vo.setUserid(e.getUserid());
            vo.setRemark(e.getRemark());
            vo.setEndtime(e.getEndtime());
            vo.setResulttable(e.getResulttable());
            vo.setResultcolumns(e.getResultcolumns());
            return vo;
        }).collect(Collectors.toList());
    }

   /* @Override
    public Result queryProblemGroupByModelId(String modelId, Integer pageNum, Integer pageSize) {
        // 先查询模型运行记录
        TModelRunRecord record = tModelRunRecordMapper.selectOne(
                new LambdaQueryWrapper<TModelRunRecord>()
                        .eq(TModelRunRecord::getModelid, modelId)
                        .eq(TModelRunRecord::getRuntype, "01")
                        .eq(TModelRunRecord::getRunstatus, "01")
                        .eq(TModelRunRecord::getRunprocess, "5")
                        .orderByDesc(TModelRunRecord::getEndtime)
                        .last("limit 1")
        );
        if (record == null) {
            return new Result();
        }
        String table = record.getResulttable();
        String resultColumns = record.getResultcolumns();
        List<ModelColumnInfo> modelColumnInfoList = JSON.parseArray(resultColumns, ModelColumnInfo.class);
        List<String> groupColumns = groupRule.getOrDefault(modelId, Collections.emptyList());
        String sql = "";
        String totalSql = "";
        //是否分组1-是，0-否
        int isgroup = 0;
        // 获取中英文列名映射关系
        Map<String, String> columnNameMap = modelColumnInfoList.stream()
                .collect(Collectors.toMap(
                        ModelColumnInfo::getEnname,
                        ModelColumnInfo::getCnname,
                        (existing, replacement) -> existing,  // 如果有重复键，保留现有的
                        LinkedHashMap::new  // 使用LinkedHashMap保持插入顺序
                ));

        if (CollectionUtil.isEmpty(groupColumns)) {
            List<String> columns = modelColumnInfoList.stream().map(ModelColumnInfo::getEnname).collect(Collectors.toList());
            totalSql = "select " + String.join(",", columns) + " from DIMENRESULT." + table;
            sql = "select " + String.join(",", columns) + " from DIMENRESULT." + table + " LIMIT " + pageSize + " OFFSET " + ((pageNum - 1) * pageSize);
        } else {
            isgroup = 1;
            List<String> columns = groupColumns.stream().map(e -> modelColumnInfoList.stream().filter(item -> item.getCnname().equals(e)).findFirst().map(ModelColumnInfo::getEnname).orElse(e)).collect(Collectors.toList());
            totalSql = "select distinct " + String.join(",", columns) + " from DIMENRESULT." + table;
            sql = "select distinct " + String.join(",", columns) + " from DIMENRESULT." + table + " LIMIT " + pageSize + " OFFSET " + ((pageNum - 1) * pageSize);
        }
        final int isGroup = isgroup;
        List<LinkedHashMap<String, Object>> dataList = reportMapper.getResultList(sql);
        List<LinkedHashMap<String, Object>> total = reportMapper.getResultList(totalSql);
        dataList.stream().forEach(data -> data.put("tableName", table));
        dataList.stream().forEach(data -> data.put("isGroup", isGroup));

        Result<Object> result = new Result<>();
        result.setResult(dataList);
        result.setCode(200);
        result.setTotal((long) total.size());
        // 将列名映射关系放入result中
        result.setColumnNameMap(columnNameMap);
        return result;
    }*/


    @Override
    public Result queryProblemGroupByModelId(String modelId, Integer pageNum, Integer pageSize, String keyword) {
        // 先查询模型运行记录
        TModelRunRecord record = tModelRunRecordMapper.selectOne(
                new LambdaQueryWrapper<TModelRunRecord>()
                        .eq(TModelRunRecord::getModelid, modelId)
                        .eq(TModelRunRecord::getRuntype, "01")
                        .eq(TModelRunRecord::getRunstatus, "01")
                        .eq(TModelRunRecord::getRunprocess, "5")
                        .orderByDesc(TModelRunRecord::getEndtime)
                        .last("limit 1")
        );
        if (record == null) {
            return new Result();
        }
        String table = record.getResulttable();
        String resultColumns = record.getResultcolumns();
        List<ModelColumnInfo> modelColumnInfoList = JSON.parseArray(resultColumns, ModelColumnInfo.class);
        List<String> groupColumns = groupRule.getOrDefault(modelId, Collections.emptyList());

        //是否分组1-是，0-否
        int isgroup = 0;
        // 获取中英文列名映射关系
        Map<String, String> columnNameMap = modelColumnInfoList.stream()
                .collect(Collectors.toMap(
                        ModelColumnInfo::getEnname,
                        ModelColumnInfo::getCnname,
                        (existing, replacement) -> existing,  // 如果有重复键，保留现有的
                        LinkedHashMap::new  // 使用LinkedHashMap保持插入顺序
                ));

        // 构建基础SQL和查询列
        List<String> columns;
        boolean isGroup = !CollectionUtil.isEmpty(groupColumns);

        if (!isGroup) {
            columns = modelColumnInfoList.stream().map(ModelColumnInfo::getEnname).collect(Collectors.toList());
        } else {
            isgroup = 1;
            columns = groupColumns.stream()
                    .map(e -> modelColumnInfoList.stream()
                            .filter(item -> item.getCnname().equals(e))
                            .findFirst()
                            .map(ModelColumnInfo::getEnname)
                            .orElse(e))
                    .collect(Collectors.toList());
        }

        String columnStr = String.join(",", columns);
        String baseFromClause = " from DIMENRESULT." + table;
        String baseSelect = isGroup ? "select distinct " + columnStr : "select " + columnStr;

        // 构建SQL和参数
        String totalSql = baseSelect + baseFromClause;
        String dataSql = baseSelect + baseFromClause;

        List<Object> totalParams = new ArrayList<>();
        List<Object> dataParams = new ArrayList<>();

        // 添加模糊查询条件
        if (StringUtils.hasText(keyword)) {
            String likePattern = "%" + keyword + "%";
            List<String> likeConditions = new ArrayList<>();

            for (String column : columns) {
                likeConditions.add(column + " LIKE ?");
            }

            String whereClause = " WHERE " + String.join(" OR ", likeConditions);
            totalSql += whereClause;
            dataSql += whereClause;

            // 添加模糊查询参数
            for (String column : columns) {
                totalParams.add(likePattern);
                dataParams.add(likePattern);
            }
        }

        // 添加分页参数
        dataSql += " LIMIT ? OFFSET ?";
        dataParams.add(pageSize);
        dataParams.add((pageNum - 1) * pageSize);

        final int isGroupFinal = isgroup;

        // 使用JdbcTemplate执行查询
        List<LinkedHashMap<String, Object>> dataList = jdbcTemplate.query(dataSql, dataParams.toArray(), (rs, rowNum) -> {
            LinkedHashMap<String, Object> row = new LinkedHashMap<>();
            for (String column : columns) {
                row.put(column, rs.getObject(column));
            }
            row.put("tableName", table);
            row.put("isGroup", isGroupFinal);
            return row;
        });

        // 查询总数
        List<LinkedHashMap<String, Object>> total = jdbcTemplate.query(totalSql, totalParams.toArray(), (rs, rowNum) -> {
            LinkedHashMap<String, Object> row = new LinkedHashMap<>();
            for (String column : columns) {
                row.put(column, rs.getObject(column));
            }
            return row;
        });

        Result<Object> result = new Result<>();
        result.setResult(dataList);
        result.setCode(200);
        result.setTotal((long) total.size());
        // 将列名映射关系放入result中
        result.setColumnNameMap(columnNameMap);
        return result;
    }

    @Override
    public Result getDetils(JsonFieldsVo vo) {
        JSONObject json = JSON.parseObject(vo.getJsonFields());
        // 获取表名
        String tableName = json.getString("tableName");
        if (tableName == null) {
            throw new IllegalArgumentException("tableName不能为空");
        }

        StringBuilder sql = new StringBuilder("SELECT * FROM DIMENRESULT.");
        StringBuilder totalSql = new StringBuilder("SELECT COUNT(*) FROM DIMENRESULT.");
        sql.append(tableName);
        totalSql.append(tableName);
        // 构建WHERE条件（排除tableName字段）
        List<String> conditions = new ArrayList<>();
        for (String key : json.keySet()) {
            if (!"tableName".equals(key) && !"isGroup".equals(key)) {
                Object value = json.get(key);
                if (ObjectUtils.isNull(value)) {
                    break;
                }
                if (value instanceof String) {
                    conditions.add(key + " = '" + escapeSql(value.toString()) + "'");
                } else if (value instanceof Number) {
                    conditions.add(key + " = " + value);
                } else if (value instanceof Boolean) {
                    conditions.add(key + " = " + value);
                } else {
                    conditions.add(key + " = '" + escapeSql(value.toString()) + "'");
                }
            }
        }
        // 添加固定的三个查询条件
        if (vo.getName() != null && !vo.getName().trim().isEmpty()) {
            conditions.add("name LIKE '%" + escapeSql(vo.getName().trim()) + "%'");
        }

        if (vo.getTopcategory() != null && !vo.getTopcategory().trim().isEmpty()) {
            conditions.add("TOPCATEGORY = '" + escapeSql(vo.getTopcategory().trim()) + "'");
        }

        if (vo.getSecondcategory() != null && !vo.getSecondcategory().trim().isEmpty()) {
            conditions.add("SECONDCATEGORY = '" + escapeSql(vo.getSecondcategory().trim()) + "'");
        }
        if (!conditions.isEmpty()) {
            sql.append(" WHERE ").append(String.join(" AND ", conditions)).append(" LIMIT " + vo.getPageSize() + " OFFSET " + ((vo.getPageNum() - 1) * vo.getPageSize()));
            totalSql.append(" WHERE ").append(String.join(" AND ", conditions));
        }
        List<LinkedHashMap<String, Object>> dataList = reportMapper.getResultList(sql.toString());
        Integer resultCount = reportMapper.getResultCount(totalSql.toString());
        Result<Object> result = new Result<>();
        result.setTotal(Long.valueOf(resultCount));
        result.setResult(dataList);
        return result;
    }

    @Override
    public Page<TModel> getModel(Integer pageNum, Integer pageSize, String name, String topcategory, String secondcategory) {
        Page<TModel> page = new Page<>(pageNum, pageSize);

        LambdaQueryWrapper<TModel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TModel::getIsdelete, 0);
        queryWrapper.like(TModel::getTopcategory,20);
        queryWrapper.like(TModel::getName,name);
        queryWrapper.like(TModel::getTopcategory,topcategory);
        queryWrapper.like(TModel::getSecondcategory,secondcategory);

        Page<TModel> modelPage = tModelMapper.selectPage(page, queryWrapper);
        for (TModel model : modelPage.getRecords()) {
            model.setModelType(modelCategoryMapper.getModelType(model));
            Result notChack = this.queryProblemGroupByModelId(model.getId(), 1, 10,"");
            Result alreadyChack = this.problemGroupChack(model.getId(), 1, 10, "","");
            model.setNotChack(notChack.getTotal());
            model.setAlreadyChack(alreadyChack.getTotal());
            model.setIssueCount(Optional.ofNullable(notChack.getTotal()).orElse(0L) + Optional.ofNullable(alreadyChack.getTotal()).orElse(0L));
        }
        return modelPage;
    }
    @Override
    public Page<TModel> getModel(String name, String topcategory, String secondcategory, String projectName, String companyName) {
        Page<TModel> page = new Page<>();
        page.setSize(Integer.MAX_VALUE);
        Page<TModel> page2 = new Page<>();
        List<TModel> tModels = new ArrayList<>();

        LambdaQueryWrapper<TModel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TModel::getIsdelete, 0);
        queryWrapper.like(TModel::getTopcategory,20);
        queryWrapper.like(TModel::getName,name);
        queryWrapper.like(TModel::getTopcategory,topcategory);
        queryWrapper.like(TModel::getSecondcategory,secondcategory);

        Page<TModel> modelPage = tModelMapper.selectPage(page, queryWrapper);
        if (StringUtils.hasLength(projectName) || StringUtils.hasLength(companyName)) {
            for (TModel model : modelPage.getRecords()) {
                //项目名称不为空，获取运行记录
                String XM= "";//记录项目名称的字段名称
                String QY= "";//记录企业名称的字段名称
                if (StringUtils.hasLength(projectName) || StringUtils.hasLength(companyName)) {
                    TModelRunRecord record = tModelRunRecordMapper.selectOne(
                            new LambdaQueryWrapper<TModelRunRecord>()
                                    .eq(TModelRunRecord::getModelid, model.getId())
                                    .eq(TModelRunRecord::getRuntype, "01")
                                    .eq(TModelRunRecord::getRunstatus, "01")
                                    .eq(TModelRunRecord::getRunprocess, "5")
                                    .orderByDesc(TModelRunRecord::getEndtime)
                                    .last("limit 1")
                    );
                    if (record != null) {
                        String table = record.getResulttable();
                        String resultColumns = record.getResultcolumns();
                        List<ModelColumnInfo> modelColumnInfoList = JSON.parseArray(resultColumns, ModelColumnInfo.class);
                        Map<String, String> columnNameMap = modelColumnInfoList.stream()
                                .collect(Collectors.toMap(
                                        ModelColumnInfo::getEnname,
                                        ModelColumnInfo::getCnname,
                                        (existing, replacement) -> existing,  // 如果有重复键，保留现有的
                                        LinkedHashMap::new  // 使用LinkedHashMap保持插入顺序
                                ));
                        for (Map.Entry<String, String> entry : columnNameMap.entrySet()) {
                            if ("项目名称".equals(entry.getValue())) {
                                XM = entry.getKey();
                            }
                            if ("企业名称".equals(entry.getValue())) {
                                QY = entry.getKey();
                            }
                        }
                        Integer resultCount =0;
                        Integer resultCount2 =0;
                        if (StringUtils.hasLength(projectName) && StringUtils.hasLength(XM)) {
                            //模糊查询运行表是否包含项目名称
                            String sql = "select count(*) from DIMENRESULT." + table +" where " +XM +" like '%" + projectName + "%'";
                            resultCount = reportMapper.getResultCount(sql);
                        }
                        if (StringUtils.hasLength(companyName) && StringUtils.hasLength(QY)) {
                            //模糊查询运行表是否包含企业名称
                            String sql2 = "select count(*) from DIMENRESULT." + table +" where " +QY +" like '%" + companyName + "%'";
                            resultCount2 = reportMapper.getResultCount(sql2);
                        }
                        if (resultCount >0 || resultCount2 > 0) {
                            model.setModelType(modelCategoryMapper.getModelType(model));
                            Result notChack = this.queryProblemGroupByModelId(model.getId(), 1, 10,"");
                            Result alreadyChack = this.problemGroupChack(model.getId(), 1, 10, "","");
                            model.setNotChack(notChack.getTotal());
                            model.setAlreadyChack(alreadyChack.getTotal());
                            model.setIssueCount(Optional.ofNullable(notChack.getTotal()).orElse(0L) + Optional.ofNullable(alreadyChack.getTotal()).orElse(0L));
                            tModels.add(model);
                        }
                    }
                }
            }
            page2.setRecords(tModels);
            page2.setTotal(tModels.size());
            return page2;

        }else {
            for (TModel model : modelPage.getRecords()) {
                model.setModelType(modelCategoryMapper.getModelType(model));
                Result notChack = this.queryProblemGroupByModelId(model.getId(), 1, 10,"");
                Result alreadyChack = this.problemGroupChack(model.getId(), 1, 10, "","");
                model.setNotChack(notChack.getTotal());
                model.setAlreadyChack(alreadyChack.getTotal());
                model.setIssueCount(Optional.ofNullable(notChack.getTotal()).orElse(0L) + Optional.ofNullable(alreadyChack.getTotal()).orElse(0L));
            }
            return modelPage;
        }
    }


    @Override
    public Result updateWorkKeyById(TModel tModel) {
        // 确保tModel中包含id字段和workKey字段
        int updateCount = tModelMapper.updateById(tModel);
        if (updateCount > 0) {
            return Result.ok(updateCount);
        } else {
            return Result.error("更新失败");
        }
    }

    @Override
    public Result<Integer> updateIsSupervise(JsonFieldsVo vo) {
        JSONObject jsonObject = JSON.parseObject(vo.getJsonFields());
        String tableName = jsonObject.getString("tableName");

        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("UPDATE DIMENRESULT.").append(tableName).append(" SET ISSUPERVISE = 1 WHERE 1=1");

        List<Object> params = new ArrayList<>();

        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();

            if ("tableName".equals(key) || "isGroup".equals(key)) {
                continue;
            }

            sqlBuilder.append(" AND ").append(key);

            if (value == null) {
                sqlBuilder.append(" IS NULL");
            } else {
                sqlBuilder.append(" = ?");
                params.add(value);
            }
        }

        String sql = sqlBuilder.toString();

        try {
            int result = jdbcTemplate.update(sql, params.toArray());
            return Result.ok(result);
        } catch (Exception e) {
            System.err.println("SQL执行失败: " + sql);
            e.printStackTrace();
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    @Override
    public Result alreadySupervise(String modelId, Integer pageNum, Integer pageSize, String keyword) {
        // 先查询模型运行记录
        TModelRunRecord record = tModelRunRecordMapper.selectOne(
                new LambdaQueryWrapper<TModelRunRecord>()
                        .eq(TModelRunRecord::getModelid, modelId)
                        .eq(TModelRunRecord::getRuntype, "01")
                        .eq(TModelRunRecord::getRunstatus, "01")
                        .eq(TModelRunRecord::getRunprocess, "5")
                        .orderByDesc(TModelRunRecord::getEndtime)
                        .last("limit 1")
        );
        if (record == null) {
            return new Result();
        }
        String table = record.getResulttable() + "_chack";
        String resultColumns = record.getResultcolumns();
        List<ModelColumnInfo> modelColumnInfoList = JSON.parseArray(resultColumns, ModelColumnInfo.class);
        List<String> groupColumns = groupRule.getOrDefault(modelId, Collections.emptyList());

        // 获取中英文列名映射关系
        Map<String, String> columnNameMap = modelColumnInfoList.stream()
                .collect(Collectors.toMap(
                        ModelColumnInfo::getEnname,
                        ModelColumnInfo::getCnname,
                        (existing, replacement) -> existing,
                        LinkedHashMap::new
                ));

        // 是否分组1-是，0-否
        int isgroup = 0;
        List<LinkedHashMap<String, Object>> dataList;
        List<LinkedHashMap<String, Object>> total;

        try {
            // 获取所有英文列名
            List<String> allColumns = modelColumnInfoList.stream()
                    .map(ModelColumnInfo::getEnname)
                    .collect(Collectors.toList());

            // 构建基础查询
            String baseColumns;
            String distinctClause = "";

            if (CollectionUtil.isEmpty(groupColumns)) {
                baseColumns = String.join(",", allColumns) + ", GROUP_ID";
            } else {
                isgroup = 1;
                List<String> columns = groupColumns.stream()
                        .map(e -> modelColumnInfoList.stream()
                                .filter(item -> item.getCnname().equals(e))
                                .findFirst()
                                .map(ModelColumnInfo::getEnname)
                                .orElse(e))
                        .collect(Collectors.toList());
                baseColumns = String.join(",", columns) + ", GROUP_ID";
                distinctClause = "DISTINCT ";
            }

            // 构建 WHERE 条件
            List<String> conditions = new ArrayList<>();
            List<Object> params = new ArrayList<>();
            List<Object> totalParams = new ArrayList<>();

            // ISDEAL 条件
            conditions.add("ISSUPERVISE == 1");

            // 模糊查询条件
            if (keyword != null && !keyword.trim().isEmpty()) {
                String searchPattern = "%" + keyword.trim() + "%";

                // 构建所有文本类型列的模糊查询条件
                String searchCondition = allColumns.stream()
                        .map(column -> column + " LIKE ?")
                        .collect(Collectors.joining(" OR "));

                conditions.add("(" + searchCondition + ")");

                // 为每个列添加相同的参数值
                for (int i = 0; i < allColumns.size(); i++) {
                    params.add(searchPattern);
                    totalParams.add(searchPattern);
                }
            }

            // 构建完整的 SQL
            String baseQuery = "SELECT " + distinctClause + baseColumns + " FROM DIMENRESULT." + table;

            // 添加 WHERE 条件
            String whereClause = "";
            if (!conditions.isEmpty()) {
                whereClause = " WHERE " + String.join(" AND ", conditions);
            }

            String totalSql = baseQuery + whereClause;
            String sql = baseQuery + whereClause + " LIMIT ? OFFSET ?";

            // 添加分页参数
            params.add(pageSize);
            params.add((pageNum - 1) * pageSize);

            final int isGroup = isgroup;

            // 查询数据
            dataList = jdbcTemplate.query(sql, params.toArray(), (rs, rowNum) -> {
                LinkedHashMap<String, Object> row = new LinkedHashMap<>();
                ResultSetMetaData metaData = rs.getMetaData();
                int columnCount = metaData.getColumnCount();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnName(i);
                    Object value = rs.getObject(i);
                    row.put(columnName, value);
                }
                row.put("tableName", table);
                row.put("isGroup", isGroup);
                return row;
            });

            // 查询总数
            total = jdbcTemplate.query(totalSql, totalParams.toArray(), (rs, rowNum) -> {
                LinkedHashMap<String, Object> row = new LinkedHashMap<>();
                ResultSetMetaData metaData = rs.getMetaData();
                int columnCount = metaData.getColumnCount();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnName(i);
                    Object value = rs.getObject(i);
                    row.put(columnName, value);
                }
                return row;
            });

        } catch (Exception e) {
            Result<Object> result = new Result<>();
            result.setColumnNameMap(columnNameMap);
            result.setCode(200);
            return result;
        }

        Result<Object> result = new Result<>();
        result.setResult(dataList);
        result.setCode(200);
        result.setTotal((long) total.size());
        result.setColumnNameMap(columnNameMap);
        return result;
    }

    @Override
    public int chackIsIssue(String originalTableName, Map<String, Object> groupFields, int isIssue) {
        //int isIssue  是否为问题，1-是，2-否
        //根据原表名建新的chack表
        //根据原表名建立新的核查chack表
        createCheckTableSimple(originalTableName);
        //根据分组查询字段查出所有内容并插入新表
        String checkTableName = originalTableName + "_chack";

        // 2. 构建正确的WHERE条件（使用分组字段，不是方法参数名）
        String whereClause = buildCorrectWhereClause(groupFields);

        // 3. 先删除核查表中可能存在的重复数据
        deleteExistingCheckData(checkTableName, whereClause);

        // 4. 插入数据到核查表
        int insertedRows = insertDataToCheckTable(originalTableName, checkTableName, whereClause, isIssue);
        //删除原表中核查的数据
        deleteExistingCheckData(originalTableName, whereClause);
        System.out.println("核查标记完成，插入行数: " + insertedRows);
        return 1;
    }

/*    @Override
    public Result problemGroupChack(String modelId, Integer pageNum, Integer pageSize,String isDeal) {
        // 先查询模型运行记录
        TModelRunRecord record = tModelRunRecordMapper.selectOne(
                new LambdaQueryWrapper<TModelRunRecord>()
                        .eq(TModelRunRecord::getModelid, modelId)
                        .eq(TModelRunRecord::getRuntype, "01")
                        .eq(TModelRunRecord::getRunstatus, "01")
                        .eq(TModelRunRecord::getRunprocess, "5")
                        .orderByDesc(TModelRunRecord::getEndtime)
                        .last("limit 1")
        );
        if (record == null) {
            return new Result();
        }
        String table = record.getResulttable() +"_chack";
        String resultColumns = record.getResultcolumns();
        List<ModelColumnInfo> modelColumnInfoList = JSON.parseArray(resultColumns, ModelColumnInfo.class);
        List<String> groupColumns = groupRule.getOrDefault(modelId, Collections.emptyList());
        String sql = "";
        String totalSql = "";
        //是否分组1-是，0-否
        int isgroup = 0;
        // 获取中英文列名映射关系
        Map<String, String> columnNameMap = null;
        List<LinkedHashMap<String, Object>> dataList = null;
        List<LinkedHashMap<String, Object>> total = null;
        try {
            columnNameMap = modelColumnInfoList.stream()
                    .collect(Collectors.toMap(
                            ModelColumnInfo::getEnname,
                            ModelColumnInfo::getCnname,
                            (existing, replacement) -> existing,  // 如果有重复键，保留现有的
                            LinkedHashMap::new  // 使用LinkedHashMap保持插入顺序
                    ));

            if (CollectionUtil.isEmpty(groupColumns)) {
                List<String> columns = modelColumnInfoList.stream().map(ModelColumnInfo::getEnname).collect(Collectors.toList());
//                totalSql = "select " + String.join(",", columns) + " from DIMENRESULT." + table;
//                sql = "select " + String.join(",", columns) + " from DIMENRESULT." + table + " LIMIT " + pageSize + " OFFSET " + ((pageNum - 1) * pageSize);
                String baseQuery = "select " + String.join(",", columns) +" , GROUP_ID "+ " from DIMENRESULT." + table;
                StringBuilder totalSqlBuilder = new StringBuilder(baseQuery);
                StringBuilder sqlBuilder = new StringBuilder(baseQuery);
                // 添加 ISDEAL 条件
                if (isDeal != null && !isDeal.isEmpty()) {
                    String condition = " WHERE ISDEAL = " + isDeal;
                    totalSqlBuilder.append(condition);
                    sqlBuilder.append(condition);
                }
                // 添加分页
                sqlBuilder.append(" LIMIT ").append(pageSize)
                        .append(" OFFSET ").append((pageNum - 1) * pageSize);

                totalSql = totalSqlBuilder.toString();
                sql = sqlBuilder.toString();
            } else {
                isgroup = 1;
                List<String> columns = groupColumns.stream().map(e -> modelColumnInfoList.stream().filter(item -> item.getCnname().equals(e)).findFirst().map(ModelColumnInfo::getEnname).orElse(e)).collect(Collectors.toList());
//                totalSql = "select distinct " + String.join(",", columns) + " from DIMENRESULT." + table;
//                sql = "select distinct " + String.join(",", columns) + " from DIMENRESULT." + table + " LIMIT " + pageSize + " OFFSET " + ((pageNum - 1) * pageSize);
                String baseQuery = "select distinct " + String.join(",", columns) +" , GROUP_ID "+ " from DIMENRESULT." + table;
                StringBuilder totalSqlBuilder = new StringBuilder(baseQuery);
                StringBuilder sqlBuilder = new StringBuilder(baseQuery);
                // 添加 ISDEAL 条件
                if (isDeal != null && !isDeal.isEmpty()) {
                    String condition = " WHERE ISDEAL = " + isDeal;
                    totalSqlBuilder.append(condition);
                    sqlBuilder.append(condition);
                }
                // 添加分页
                sqlBuilder.append(" LIMIT ").append(pageSize)
                        .append(" OFFSET ").append((pageNum - 1) * pageSize);

                totalSql = totalSqlBuilder.toString();
                sql = sqlBuilder.toString();
            }
            final int isGroup = isgroup;
            dataList = reportMapper.getResultList(sql);
            total = reportMapper.getResultList(totalSql);
            dataList.stream().forEach(data -> data.put("tableName", table));
            dataList.stream().forEach(data -> data.put("isGroup", isGroup));
        } catch (Exception e) {
            Result<Object> result = new Result<>();
            result.setColumnNameMap(columnNameMap);
            result.setCode(200);
            return result;
        }

        //问题描述
//        dataList = addIssueDescription(modelId,columnNameMap,dataList);
        Result<Object> result = new Result<>();
        result.setResult(dataList);
        result.setCode(200);
        result.setTotal((long) total.size());
        // 将列名映射关系放入result中
        result.setColumnNameMap(columnNameMap);
        return result;
    }*/

    @Override
    public Result problemGroupChack(String modelId, Integer pageNum, Integer pageSize, String isDeal, String keyword) {
        // 先查询模型运行记录
        TModelRunRecord record = tModelRunRecordMapper.selectOne(
                new LambdaQueryWrapper<TModelRunRecord>()
                        .eq(TModelRunRecord::getModelid, modelId)
                        .eq(TModelRunRecord::getRuntype, "01")
                        .eq(TModelRunRecord::getRunstatus, "01")
                        .eq(TModelRunRecord::getRunprocess, "5")
                        .orderByDesc(TModelRunRecord::getEndtime)
                        .last("limit 1")
        );
        if (record == null) {
            return new Result();
        }
        String table = record.getResulttable() + "_chack";
        String resultColumns = record.getResultcolumns();
        List<ModelColumnInfo> modelColumnInfoList = JSON.parseArray(resultColumns, ModelColumnInfo.class);
        List<String> groupColumns = groupRule.getOrDefault(modelId, Collections.emptyList());

        // 获取中英文列名映射关系
        Map<String, String> columnNameMap = modelColumnInfoList.stream()
                .collect(Collectors.toMap(
                        ModelColumnInfo::getEnname,
                        ModelColumnInfo::getCnname,
                        (existing, replacement) -> existing,
                        LinkedHashMap::new
                ));

        // 是否分组1-是，0-否
        int isgroup = 0;
        List<LinkedHashMap<String, Object>> dataList;
        List<LinkedHashMap<String, Object>> total;

        try {
            // 获取所有英文列名
            List<String> allColumns = modelColumnInfoList.stream()
                    .map(ModelColumnInfo::getEnname)
                    .collect(Collectors.toList());

            // 构建基础查询
            String baseColumns;
            String distinctClause = "";

            if (CollectionUtil.isEmpty(groupColumns)) {
                baseColumns = String.join(",", allColumns) + ", GROUP_ID";
            } else {
                isgroup = 1;
                List<String> columns = groupColumns.stream()
                        .map(e -> modelColumnInfoList.stream()
                                .filter(item -> item.getCnname().equals(e))
                                .findFirst()
                                .map(ModelColumnInfo::getEnname)
                                .orElse(e))
                        .collect(Collectors.toList());
                baseColumns = String.join(",", columns) + ", GROUP_ID";
                distinctClause = "DISTINCT ";
            }

            // 构建 WHERE 条件
            List<String> conditions = new ArrayList<>();
            List<Object> params = new ArrayList<>();
            List<Object> totalParams = new ArrayList<>();

            // ISDEAL 条件
            if (isDeal != null && !isDeal.isEmpty()) {
                conditions.add("ISDEAL = ?");
                params.add(isDeal);
                totalParams.add(isDeal);
            }

            // 模糊查询条件
            if (keyword != null && !keyword.trim().isEmpty()) {
                String searchPattern = "%" + keyword.trim() + "%";

                // 构建所有文本类型列的模糊查询条件
                String searchCondition = allColumns.stream()
                        .map(column -> column + " LIKE ?")
                        .collect(Collectors.joining(" OR "));

                conditions.add("(" + searchCondition + ")");

                // 为每个列添加相同的参数值
                for (int i = 0; i < allColumns.size(); i++) {
                    params.add(searchPattern);
                    totalParams.add(searchPattern);
                }
            }

            // 构建完整的 SQL
            String baseQuery = "SELECT " + distinctClause + baseColumns + " FROM DIMENRESULT." + table;

            // 添加 WHERE 条件
            String whereClause = "";
            if (!conditions.isEmpty()) {
                whereClause = " WHERE " + String.join(" AND ", conditions);
            }

            String totalSql = baseQuery + whereClause;
            String sql = baseQuery + whereClause + " LIMIT ? OFFSET ?";

            // 添加分页参数
            params.add(pageSize);
            params.add((pageNum - 1) * pageSize);

            final int isGroup = isgroup;

            // 查询数据
            dataList = jdbcTemplate.query(sql, params.toArray(), (rs, rowNum) -> {
                LinkedHashMap<String, Object> row = new LinkedHashMap<>();
                ResultSetMetaData metaData = rs.getMetaData();
                int columnCount = metaData.getColumnCount();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnName(i);
                    Object value = rs.getObject(i);
                    row.put(columnName, value);
                }
                row.put("tableName", table);
                row.put("isGroup", isGroup);
                return row;
            });

            // 查询总数
            total = jdbcTemplate.query(totalSql, totalParams.toArray(), (rs, rowNum) -> {
                LinkedHashMap<String, Object> row = new LinkedHashMap<>();
                ResultSetMetaData metaData = rs.getMetaData();
                int columnCount = metaData.getColumnCount();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnName(i);
                    Object value = rs.getObject(i);
                    row.put(columnName, value);
                }
                return row;
            });

        } catch (Exception e) {
            Result<Object> result = new Result<>();
            result.setColumnNameMap(columnNameMap);
            result.setCode(200);
            return result;
        }
        //问题描述
        dataList = addIssueDescription(modelId,columnNameMap,dataList);
        Result<Object> result = new Result<>();
        result.setResult(dataList);
        result.setCode(200);
        result.setTotal((long) total.size());
        result.setColumnNameMap(columnNameMap);
        return result;
    }
    @Override
    public Result notComplete(String modelId, Integer pageNum, Integer pageSize, String keyword) {
        // 先查询模型运行记录
        TModelRunRecord record = tModelRunRecordMapper.selectOne(
                new LambdaQueryWrapper<TModelRunRecord>()
                        .eq(TModelRunRecord::getModelid, modelId)
                        .eq(TModelRunRecord::getRuntype, "01")
                        .eq(TModelRunRecord::getRunstatus, "01")
                        .eq(TModelRunRecord::getRunprocess, "5")
                        .orderByDesc(TModelRunRecord::getEndtime)
                        .last("limit 1")
        );
        if (record == null) {
            return new Result();
        }
        String endtime = record.getEndtime();
        String table = record.getResulttable() + "_chack";
        String resultColumns = record.getResultcolumns();
        List<ModelColumnInfo> modelColumnInfoList = JSON.parseArray(resultColumns, ModelColumnInfo.class);
        List<String> groupColumns = groupRule.getOrDefault(modelId, Collections.emptyList());

        // 获取中英文列名映射关系
        Map<String, String> columnNameMap = modelColumnInfoList.stream()
                .collect(Collectors.toMap(
                        ModelColumnInfo::getEnname,
                        ModelColumnInfo::getCnname,
                        (existing, replacement) -> existing,
                        LinkedHashMap::new
                ));

        // 是否分组1-是，0-否
        int isgroup = 0;
        List<LinkedHashMap<String, Object>> dataList;
        List<LinkedHashMap<String, Object>> total;

        try {
            // 获取所有英文列名
            List<String> allColumns = modelColumnInfoList.stream()
                    .map(ModelColumnInfo::getEnname)
                    .collect(Collectors.toList());

            // 构建基础查询
            String baseColumns;
            String distinctClause = "";

            if (CollectionUtil.isEmpty(groupColumns)) {
                baseColumns = String.join(",", allColumns) + ", GROUP_ID  , INITIATIONTIME";
            } else {
                isgroup = 1;
                List<String> columns = groupColumns.stream()
                        .map(e -> modelColumnInfoList.stream()
                                .filter(item -> item.getCnname().equals(e))
                                .findFirst()
                                .map(ModelColumnInfo::getEnname)
                                .orElse(e))
                        .collect(Collectors.toList());
                baseColumns = String.join(",", columns) + ", GROUP_ID , INITIATIONTIME";
                distinctClause = "DISTINCT ";
            }

            // 构建 WHERE 条件
            List<String> conditions = new ArrayList<>();
            List<Object> params = new ArrayList<>();
            List<Object> totalParams = new ArrayList<>();

            // ISDEAL 条件
            conditions.add("ISDEAL IN (2,3)");

            // 模糊查询条件
            if (keyword != null && !keyword.trim().isEmpty()) {
                String searchPattern = "%" + keyword.trim() + "%";

                // 构建所有文本类型列的模糊查询条件
                String searchCondition = allColumns.stream()
                        .map(column -> column + " LIKE ?")
                        .collect(Collectors.joining(" OR "));

                conditions.add("(" + searchCondition + ")");

                // 为每个列添加相同的参数值
                for (int i = 0; i < allColumns.size(); i++) {
                    params.add(searchPattern);
                    totalParams.add(searchPattern);
                }
            }

            // 构建完整的 SQL
            String baseQuery = "SELECT " + distinctClause + baseColumns + " FROM DIMENRESULT." + table;

            // 添加 WHERE 条件
            String whereClause = "";
            if (!conditions.isEmpty()) {
                whereClause = " WHERE " + String.join(" AND ", conditions);
            }

            String totalSql = baseQuery + whereClause;
            String sql = baseQuery + whereClause + " LIMIT ? OFFSET ?";

            // 添加分页参数
            params.add(pageSize);
            params.add((pageNum - 1) * pageSize);

            final int isGroup = isgroup;

            // 查询数据
            dataList = jdbcTemplate.query(sql, params.toArray(), (rs, rowNum) -> {
                LinkedHashMap<String, Object> row = new LinkedHashMap<>();
                ResultSetMetaData metaData = rs.getMetaData();
                int columnCount = metaData.getColumnCount();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnName(i);
                    Object value = rs.getObject(i);
                    row.put(columnName, value);
                }
                row.put("tableName", table);
                row.put("isGroup", isGroup);
                return row;
            });

            // 查询总数
            total = jdbcTemplate.query(totalSql, totalParams.toArray(), (rs, rowNum) -> {
                LinkedHashMap<String, Object> row = new LinkedHashMap<>();
                ResultSetMetaData metaData = rs.getMetaData();
                int columnCount = metaData.getColumnCount();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnName(i);
                    Object value = rs.getObject(i);
                    row.put(columnName, value);
                }
                return row;
            });
            dataList.forEach(d ->{
                d.putIfAbsent("INITIATIONTIME", endtime);
            });

        } catch (Exception e) {
            Result<Object> result = new Result<>();
            result.setColumnNameMap(columnNameMap);
            result.setCode(200);
            return result;
        }

        Result<Object> result = new Result<>();
        result.setResult(dataList);
        result.setCode(200);
        result.setTotal((long) total.size());
        result.setColumnNameMap(columnNameMap);
        return result;
    }

    private List<LinkedHashMap<String, Object>> addIssueDescription(String modelId, Map<String, String> columnNameMap, List<LinkedHashMap<String, Object>> dataList) {
        // 使用 LambdaQueryWrapper（更优雅）
        TModel model = tModelMapper.selectOne(
                new LambdaQueryWrapper<TModel>()
                        .eq(TModel::getId, modelId)

        );
        //issueDescription问题描述
        if ("招标公告发布时间早于项目审批、核准或备案时间".equals(model.getName())){
            //（项目名称）的招标公告发布时间早于项目审批、核准或备案时间
            String name = getProjectNameKey(columnNameMap);
            for (LinkedHashMap<String, Object> map : dataList) {
                String project = (String)map.get(name);
                map.put("issueDescription",project+"的招标公告发布时间早于项目审批、核准或备案时间");
            }
            return dataList;
        } else if ("招标公告发布时间在项目审批、核准或备案文件有效期届满之后".equals(model.getName())){
            //（项目名称）的招标公告发布时间在项目审批、核准或备案文件有效期届满之后
            String name = getProjectNameKey(columnNameMap);
            for (LinkedHashMap<String, Object> map : dataList) {
                String project = (String)map.get(name);
                map.put("issueDescription",project+"的招标公告发布时间在项目审批、核准或备案文件有效期届满之后");
            }
            return dataList;
        } else if ("依法必须招标的项目，未通过指定媒介发布招标公告".equals(model.getName())) {
            //（项目名称）未通过指定媒介发布招标公告
            String name = getProjectNameKey(columnNameMap);
            for (LinkedHashMap<String, Object> map : dataList) {
                String project = (String)map.get(name);
                map.put("issueDescription",project+"未通过指定媒介发布招标公告");
            }
            return dataList;
        } else if ("依法必须招标的项目，未在招标公告中载明提出异议的渠道".equals(model.getName())) {
            //（项目名称）未在招标公告中载明提出异议的渠道
            String name = getProjectNameKey(columnNameMap);
            for (LinkedHashMap<String, Object> map : dataList) {
                String project = (String)map.get(name);
                map.put("issueDescription",project+"未在招标公告中载明提出异议的渠道");
            }
            return dataList;
        } else if ("依法必须招标的项目，从招标文件发出至投标截至日不足20日".equals(model.getName())) {
            //（项目名称）从招标文件发出至投标截至日不足20日
            String name = getProjectNameKey(columnNameMap);
            for (LinkedHashMap<String, Object> map : dataList) {
                String project = (String)map.get(name);
                map.put("issueDescription",project+"从招标文件发出至投标截至日不足20日");
            }
            return dataList;
        } else if ("投标人一年内投标20次以上并且从未中标".equals(model.getName())) {
            //（企业名称）在（投标年份）内投标（投标数量）并且从未中标
            String name = getCompanyKey(columnNameMap);
            String name1 = getYearKey(columnNameMap);
            String name2 = getCountKey(columnNameMap);
            for (LinkedHashMap<String, Object> map : dataList) {
                String conpany = (String)map.get(name);
                String year = (String)map.get(name1);
                BigDecimal count = (BigDecimal)map.get(name2);
                map.put("issueDescription",conpany+"在"+year+"内投标"+count+"并且从未中标");
            }
            return dataList;
        } else if ("同一项目中，不同投标人使用同一台电脑（MAC地址、硬盘序列号等相同）".equals(model.getName())) {
            //（项目名称）中，不同投标人使用同一台电脑（MAC地址、硬盘序列号等相同）
            String name = getProjectNameKey(columnNameMap);
            for (LinkedHashMap<String, Object> map : dataList) {
                String project = (String)map.get(name);
                map.put("issueDescription",project+"中，不同投标人使用同一台电脑（MAC地址、硬盘序列号等相同）");
            }
            return dataList;
        } else if ("同一项目中，不同投标人使用同一个IP地址上传或解密投标文件".equals(model.getName())) {
            //（项目名称）中，不同投标人使用同一个IP地址上传或解密投标文件
            String name = getProjectNameKey(columnNameMap);
            for (LinkedHashMap<String, Object> map : dataList) {
                String project = (String)map.get(name);
                map.put("issueDescription",project+"中，不同投标人使用同一个IP地址上传或解密投标文件");
            }
            return dataList;
        } else if ("同一项目中，不同投标人的联系人、电话相同".equals(model.getName())) {
            //（项目名称）中，不同投标人的联系人、电话相同
            String name = getProjectNameKey(columnNameMap);
            for (LinkedHashMap<String, Object> map : dataList) {
                String project = (String)map.get(name);
                map.put("issueDescription",project+"中，不同投标人的联系人、电话相同");
            }
            return dataList;
        } else if ("同一项目中，不同投标人的单位地址相同".equals(model.getName())) {
            //（项目名称）中，不同投标人的联系人单位地址相同
            String name = getProjectNameKey(columnNameMap);
            for (LinkedHashMap<String, Object> map : dataList) {
                String project = (String)map.get(name);
                map.put("issueDescription",project+"中，不同投标人的联系人单位地址相同");
            }
            return dataList;
        } else if ("不同投标人的投标报价呈现规律性差异".equals(model.getName())) {
            //（项目名称）中，不同投标人的投标报价呈现规律性差异
            String name = getProjectNameKey(columnNameMap);
            for (LinkedHashMap<String, Object> map : dataList) {
                String project = (String)map.get(name);
                map.put("issueDescription",project+"中，不同投标人的投标报价呈现规律性差异");
            }
            return dataList;
        } else if ("招标人在评标委员会推荐的中标候选人之外确定中标人".equals(model.getName())) {
            //（项目名称）中，招标人在评标委员会推荐的中标候选人之外确定中标人
            String name = getProjectNameKey(columnNameMap);
            for (LinkedHashMap<String, Object> map : dataList) {
                String project = (String)map.get(name);
                map.put("issueDescription",project+"中，招标人在评标委员会推荐的中标候选人之外确定中标人");
            }
            return dataList;
        } else if ("招标人无正当理由拒不定标".equals(model.getName())) {
            //（招标代理单位名称）无正当理由拒不定标
            String name = getAgentKey(columnNameMap);
            for (LinkedHashMap<String, Object> map : dataList) {
                String project = (String)map.get(name);
                map.put("issueDescription",project+"无正当理由拒不定标");
            }
            return dataList;
        } else if ("中标人以外的企业签订中标合同".equals(model.getName())) {
            //中标人以外的企业签订中标合同
            for (LinkedHashMap<String, Object> map : dataList) {
                map.put("issueDescription","中标人以外的企业签订中标合同");
            }
            return dataList;
        } else if ("项目经理变更2次以上".equals(model.getName())) {
            //（项目名称）的项目经理变更2次以上
            String name = getProjectNameKey(columnNameMap);
            for (LinkedHashMap<String, Object> map : dataList) {
                String project = (String)map.get(name);
                map.put("issueDescription",project+"的项目经理变更2次以上");
            }
            return dataList;
        } else if ("行政监督部门或其工作人员长期不登录电子监管系统账号".equals(model.getName())) {
            //（监督人员）长期不登录电子监管系统账号
            String name = getSupervisorKey(columnNameMap);
            for (LinkedHashMap<String, Object> map : dataList) {
                String project = (String)map.get(name);
                map.put("issueDescription",project+"长期不登录电子监管系统账号");
            }
            return dataList;
        } else if ("行政监督部门的工作人员担任其负责监督项目的评标委员会成员".equals(model.getName())) {
            //（监督部门）的（监督人员）担任其负责（项目名称）的评标委员会成员
            String name = getSupervisorKey(columnNameMap);
            String name1 = getSupervisPartKey(columnNameMap);
            String name2 = getProjectNameKey(columnNameMap);
            for (LinkedHashMap<String, Object> map : dataList) {
                String project = (String)map.get(name);
                String part = (String)map.get(name1);
                String projectName = (String)map.get(name2);
                map.put("issueDescription",part+"的"+project+"担任其负责"+projectName+"的评标委员会成员");
            }
            return dataList;
        } else if ("最终中标人并非公示的第一候选人".equals(model.getName())) {
            //（中标单位）并非公示的第一候选人
            String name = getWinningBidderKey(columnNameMap);
            for (LinkedHashMap<String, Object> map : dataList) {
                String project = (String)map.get(name);
                map.put("issueDescription",project+"并非公示的第一候选人");
            }
            return dataList;
        } else if ("招标代理和中标人在同一标段出现的概率超70%".equals(model.getName())) {
            //（招标代理单位名称）与（中标人）在同一标段出现的概率超70%
            String name = getBidderPartNameKey(columnNameMap);
            String name1 = getBidderPeopleKey(columnNameMap);
            for (LinkedHashMap<String, Object> map : dataList) {
                String project = (String)map.get(name);
                String project1 = (String)map.get(name1);
                map.put("issueDescription",project+"与"+project1+"在同一标段出现的概率超70%");
            }
            return dataList;
        }
        return dataList;
    };
    // 专门获取"项目名称"对应的 key
    public static String getProjectNameKey(Map<String, String> columnNameMap) {
        for (Map.Entry<String, String> entry : columnNameMap.entrySet()) {
            if ("项目名称".equals(entry.getValue())) {
                return entry.getKey();
            }
        }
        return null;
    }
    // 专门获取"企业名称"对应的 key
    public static String getCompanyKey(Map<String, String> columnNameMap) {
        for (Map.Entry<String, String> entry : columnNameMap.entrySet()) {
            if ("企业名称".equals(entry.getValue())) {
                return entry.getKey();
            }
        }
        return null;
    }
    // 专门获取"投标年份"对应的 key
    public static String getYearKey(Map<String, String> columnNameMap) {
        for (Map.Entry<String, String> entry : columnNameMap.entrySet()) {
            if ("投标年份".equals(entry.getValue())) {
                return entry.getKey();
            }
        }
        return null;
    }
    // 专门获取"投标数量"对应的 key
    public static String getCountKey(Map<String, String> columnNameMap) {
        for (Map.Entry<String, String> entry : columnNameMap.entrySet()) {
            if ("投标数量".equals(entry.getValue())) {
                return entry.getKey();
            }
        }
        return null;
    }
    // 专门获取"招标代理单位名称"对应的 key
    public static String getAgentKey(Map<String, String> columnNameMap) {
        for (Map.Entry<String, String> entry : columnNameMap.entrySet()) {
            if ("招标代理单位名称".equals(entry.getValue())) {
                return entry.getKey();
            }
        }
        return null;
    }
    // 专门获取"监督人员"对应的 key
    public static String getSupervisorKey(Map<String, String> columnNameMap) {
        for (Map.Entry<String, String> entry : columnNameMap.entrySet()) {
            if ("监督人员".equals(entry.getValue())) {
                return entry.getKey();
            }
        }
        return null;
    }
    // 专门获取"监督部门"对应的 key
    public static String getSupervisPartKey(Map<String, String> columnNameMap) {
        for (Map.Entry<String, String> entry : columnNameMap.entrySet()) {
            if ("监督部门".equals(entry.getValue())) {
                return entry.getKey();
            }
        }
        return null;
    }
    // 专门获取"中标单位"对应的 key
    public static String getWinningBidderKey(Map<String, String> columnNameMap) {
        for (Map.Entry<String, String> entry : columnNameMap.entrySet()) {
            if ("中标单位".equals(entry.getValue())) {
                return entry.getKey();
            }
        }
        return null;
    }
    // 专门获取"招标代理单位名称"对应的 key
    public static String getBidderPartNameKey(Map<String, String> columnNameMap) {
        for (Map.Entry<String, String> entry : columnNameMap.entrySet()) {
            if ("招标代理单位名称".equals(entry.getValue())) {
                return entry.getKey();
            }
        }
        return null;
    }
    // 专门获取"中标人"对应的 key
    public static String getBidderPeopleKey(Map<String, String> columnNameMap) {
        for (Map.Entry<String, String> entry : columnNameMap.entrySet()) {
            if ("中标人".equals(entry.getValue())) {
                return entry.getKey();
            }
        }
        return null;
    }

    @Override
    public Page<Map<String, Object>> getModelChack(Integer pageNum, Integer pageSize,String name,String topCategory, String secondCategory) {
        Page<Map<String, Object>> page = new Page<>(pageNum, pageSize);

        // 计算偏移量
        long offset = (pageNum - 1) * pageSize;
        // 查询分页数据
        List<Map<String, Object>> records = reportMapper.selectModelWithCheckTable(offset, pageSize,name,topCategory,secondCategory);

        // 查询总数
        Long total = reportMapper.selectModelWithCheckTableCount(name,topCategory,secondCategory);

        // 设置分页结果
        page.setRecords(records);
        page.setTotal(total);
        page.setSize(pageSize);
        page.setCurrent(pageNum);

        // 处理业务逻辑
        for (Map<String, Object> record : records) {
            Number hasCheckTable = (Number) record.get("hasCheckTable");
            if (hasCheckTable != null && hasCheckTable.intValue()>0) {
                // 存在检查表的业务逻辑
                String resultTable = (String) record.get("RESULTTABLE");
            }
            TModel tModel = new TModel();
            tModel.setId((String) record.get("ID"));
            tModel.setTopcategory((String) record.get("TOPCATEGORY"));
            tModel.setSecondcategory((String) record.get("SECONDCATEGORY"));
            //已处理、未处理数
            Result alreadyDeal = this.problemGroupChack((String) record.get("ID"), 1, 10, String.valueOf(1),"");
            Result notDeal = this.problemGroupChack((String) record.get("ID"), 1, 10, String.valueOf(2),"");
            Result dealing = this.problemGroupChack((String) record.get("ID"), 1, 10, String.valueOf(3),"");
            record.put("alreadyDeal",alreadyDeal.getTotal());
            record.put("notDeal",notDeal.getTotal());
            record.put("dealing",dealing.getTotal());
            record.put("issueCount", this.problemGroupChack(tModel.getId(), 1, 10, "","").getTotal());
            record.put("modelType",modelCategoryMapper.getModelType(tModel));
        }
        return page;
    }

    /**
     * 构建正确的WHERE条件（使用分组字段名和值）
     */
    private String buildCorrectWhereClause(Map<String, Object> groupFields) {
        if (groupFields == null || groupFields.isEmpty()) {
            throw new IllegalArgumentException("分组字段不能为空");
        }

        return groupFields.entrySet().stream()
                .map(entry -> {
                    String fieldName = entry.getKey();  // 数据库字段名，如 t5_PARAGRAPHID, g6_1 等
                    Object value = entry.getValue();
                    return buildFieldCondition(fieldName, value);
                })
                .collect(Collectors.joining(" AND "));
    }

    /**
     * 构建单个字段的条件
     */
    private String buildFieldCondition(String fieldName, Object value) {
        if (value == null) {
            return fieldName + " IS NULL";
        } else if (value instanceof String) {
            // 字符串类型，需要处理单引号转义
            String escapedValue = value.toString().replace("'", "''");
            return fieldName + " = '" + escapedValue + "'";
        } else if (value instanceof Number) {
            // 数字类型
            return fieldName + " = " + value;
        } else if (value instanceof Date) {
            // 日期类型
            java.sql.Date sqlDate = new java.sql.Date(((Date) value).getTime());
            return fieldName + " = DATE '" + sqlDate + "'";
        } else if (value instanceof Boolean) {
            // 布尔类型
            return fieldName + " = " + ((Boolean) value ? "1" : "0");
        } else {
            // 其他类型转为字符串处理
            String escapedValue = value.toString().replace("'", "''");
            return fieldName + " = '" + escapedValue + "'";
        }
    }

    /**
     * 删除核查表中已存在的数据
     */
    private void deleteExistingCheckData(String checkTableName, String whereClause) {
        try {
            String deleteSql = "DELETE FROM DIMENRESULT." + checkTableName + " WHERE " + whereClause;
            int deletedRows = jdbcTemplate.update(deleteSql);
            if (deletedRows > 0) {
                System.out.println("删除已存在核查数据: " + deletedRows + " 行");
            }
        } catch (Exception e) {
            System.err.println("删除现有核查数据失败: " + e.getMessage());
        }
    }

    /**
     * 将数据插入到核查表
     */
    private int insertDataToCheckTable(String originalTableName, String checkTableName,
                                       String whereClause, int isIssue) {
        // 获取原表的所有字段名（排除ISISSUE字段）
        List<String> columnNames = getTableColumnNames(originalTableName);

        // 构建INSERT SQL
        String insertSql = buildInsertSql(originalTableName, checkTableName, columnNames, whereClause, isIssue);

        System.out.println("执行SQL: " + insertSql); // 调试用

        // 执行插入
        return jdbcTemplate.update(insertSql);
    }

    /**
     * 获取表的所有字段名
     */
    private List<String> getTableColumnNames(String tableName) {
        String sql = "SELECT COLUMN_NAME FROM ALL_TAB_COLUMNS " +
                "WHERE OWNER = 'DIMENRESULT' AND TABLE_NAME = ? " +
                "AND COLUMN_NAME != 'ISISSUE' " +
                "ORDER BY COLUMN_ID";

        try {
            return jdbcTemplate.queryForList(sql, String.class, tableName.toUpperCase());
        } catch (Exception e) {
            throw new RuntimeException("获取表字段失败: " + tableName, e);
        }
    }

    /**
     * 构建INSERT SQL语句
     */
    private String buildInsertSql(String originalTableName, String checkTableName,
                                  List<String> columnNames, String whereClause, int isIssue) {
        StringBuilder sql = new StringBuilder();
        sql.append("INSERT INTO DIMENRESULT.").append(checkTableName).append(" (");

        // 添加所有字段名
        sql.append(String.join(", ", columnNames));
        sql.append(", ISISSUE "); // 添加ISISSUE字段是否为问题1-是，2-否
        sql.append(", ISDEAL) "); // 添加ISDEAL字段是否办理1-是，2-待办里,3-办理中

        // 添加SELECT部分
        sql.append("SELECT ");
        sql.append(String.join(", ", columnNames));
        sql.append(", ").append(isIssue).append(" as ISISSUE ");
        sql.append(", ").append(2).append(" as ISDEAL ");
        sql.append("FROM DIMENRESULT.").append(originalTableName);
        sql.append(" WHERE ").append(whereClause);

        return sql.toString();
    }
    /**
     * 简化版创建核查表
     */
    public boolean createCheckTableSimple(String originalTableName) {
        String checkTableName = originalTableName + "_chack";

        try {
            // 检查表是否已存在
            if (isTableExists(checkTableName)) {
                System.out.println("核查表已存在: " + checkTableName);
                return true;
            }

            // 使用CREATE TABLE AS语句创建表结构
            //ISISSUE 1-是2-否
            //ISDEAL 1-已办理，2-待办里，3-办理中
            //ISSUPERVISE  是否督办   1-是0-否
            //INITIATIONTIME  初始化时间
            //GROUP_ID  问题组id
            //HCZT  处理状态
            //CLQK  检查结果
            //FJSC  附件描述
            //WTSB_STATUS  问题上报状态 1 上报 2不上报
            //POINT_USER_ID  重点问题的关注人
            //POINT_DEPT_ID  重点问题的关注部门id
            String createSql = "CREATE TABLE DIMENRESULT." + checkTableName +
                    " AS SELECT t.*, " +
                    "1 as ISISSUE, 2 as ISDEAL," +
                    " 0 as ISSUPERVISE, " +
                    "CAST(NULL AS DATE) as INITIATIONTIME," +
                    "CAST('' AS VARCHAR(1500)) as GROUP_ID," +
                    "CAST('' AS VARCHAR(1500)) as WTSB_STATUS," +
                    "CAST('' AS VARCHAR(1500)) as START_TIME," +
                    "CAST('' AS VARCHAR(1500)) as POINT_USER_ID," +
                    "CAST('' AS VARCHAR(1500)) as POINT_DEPT_ID, " +
                    "CAST('' AS VARCHAR(20)) as HCZT, " +
                    "CAST('' AS varchar(5000)) as CLQK, " +
                    "CAST('' AS VARCHAR(5000)) as FJSC" +
                    "" +
                    " FROM DIMENRESULT." + originalTableName + " t WHERE 1 = 0";

            jdbcTemplate.execute(createSql);
            System.out.println("核查表创建成功: " + checkTableName);
            return true;

        } catch (Exception e) {
            if (e.getMessage().contains("表") && e.getMessage().contains("已存在")) {
                System.out.println("核查表已存在: " + checkTableName);
                return true;
            }
            System.err.println("创建核查表失败: " + e.getMessage());
            return false;
        }
    }

    private boolean isTableExists(String tableName) {
        try {
            jdbcTemplate.queryForObject(
                    "SELECT 1 FROM DIMENRESULT." + tableName + " WHERE 1 = 0",
                    Integer.class
            );
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * SQL注入防护
     */
    private static String escapeSql(String value) {
        return value.replace("'", "''");
    }

    public static Map<String, List<String>> groupRule = new HashMap<String, List<String>>() {{
//        投标人一年内投标20次以上并且从未中标 投标年份、企业名称、投标数量
        put("7854D0EDF1BBB2112189E3EDC818AE23", CollectionUtil.newArrayList("投标年份", "企业名称", "投标数量"));
//        同一项目中，不同投标人使用同一台电脑（MAC地址、硬盘序列号等相同）项目名称、标段名称、制作投标文件mac码、同一标段使用同一MAC码的单位数量
        put("61FE6CD23093B2111BBC63261B804E3A", CollectionUtil.newArrayList("项目名称", "标段名称", "制作投标文件mac码", "同一标段使用同一MAC码的单位数量"));
//        同一项目中，不同投标人使用同一个IP地址上传或解密投标文件  项目名称、标段名称、使用同一IP地址上传文件的单位数量、招标文件上传IP地址
        put("483497EF3093B211249FAC81AE10F762", CollectionUtil.newArrayList("项目名称", "标段名称", "使用同一IP地址上传文件的单位数量", "招标文件上传IP地址"));
//        同一项目中，不同投标人的联系人、电话相同  投标联系人、投标联系人电话、组合数量、项目名称、标段名称、招标公告标题、中标人
        put("9D9B41063193B2119B94AA4EE543D732", CollectionUtil.newArrayList("投标联系人", "投标联系人电话", "组合数量", "项目名称", "标段名称", "招标公告标题"));
//        同一项目中，不同投标单位的地址相同   项目名称、标段名称、招标公告标题、单位注册地址、组合数量
        put("6E9B814928B0B21128BBBE8B07113612", CollectionUtil.newArrayList("项目名称", "标段名称", "招标公告标题", "单位注册地址", "组合数量"));
//        招标代理与中标人异常关联   企业、招标代理单位名称、特定代理的投标次数、特定代理的中标次数、特定代理下的中标率、投标次数、中标次数、中标率、概率差值
        put("84265AEA4297B211D99FF5FE89F76C56", CollectionUtil.newArrayList("企业名称","招标代理单位名称","特定代理的投标次数","特定代理的中标次数","特定代理下的中标率","投标次数","中标次数","中标率","概率差值"));
        //不同投标人一年内共同投标15次以上，并且合计中标5次以上     年份、组合投标企业名称1、组合投标企业名称2、组合投标企业名称3、组合投标次数、组合中标次数
        put("26B8693853BBB211E1A5C99A7FE7323F", CollectionUtil.newArrayList("年份", "组合投标次数", "组合投标企业名称1", "组合投标企业名称2","组合投标企业名称3","组合中标次数"));

    }};

    public static Map<String, List<String>> groupRule1 = new HashMap<String, List<String>>() {{
//        投标人一年内投标20次以上并且从未中标 投标年份、企业名称、投标数量
//        [{"colType":"STRING","cnname":"企业名称","enname":"t18_NAME"},{"colType":"STRING","cnname":"年份","enname":"g14_1"},{"colType":"INT","cnname":"投标次数","enname":"g6_1"}]
        put("71912DA43093B21120B22B7E4570203C", CollectionUtil.newArrayList("g14_1", "t18_NAME", "g6_1"));
//        同一项目中，不同投标人使用同一台电脑（MAC地址、硬盘序列号等相同）项目名称、标段名称、制作投标文件mac码、同一标段使用同一MAC码的单位数量、开标日期、中标人
//        {"nodes":[{"data":{"id":"1","type":"unbundled-bezier(multiple)","nodeType":"T01","up":[],"down":["2"],"name":"施工图设计终审表","stcId":"FA7E02912E93B211B88B5EC6EF019138","catalog":"dameng5","schema":"DIMENMODEL","table":"API_CONSTRUCTION_DRAWING_FINAL_REVIEW","columns":[{"id":"312004912E93B21127BB4EA17A44C407","sourceId":"83DAC98D2E93B211B6B9511F593E883A","enname":"PROJECTNAME","cnname":"项目名称","pid":"FA7E02912E93B211B88B5EC6EF019138","type":"column","comments":"项目名称","colType":"VARCHAR2","colCommonUsed":"1","colRelation":"0","attribute":null,"colDic":null,"attributeValue":null,"coldicValue":null,"checked":true,"colControl":null,"nodeId":"1"},{"id":"C5A304912E93B2117CAA5B4CF5E46014","sourceId":"83DAC98D2E93B211B6B9511F593E883A","enname":"PROJECTCODE","cnname":"项目编号","pid":"FA7E02912E93B211B88B5EC6EF019138","type":"column","comments":"项目编号","colType":"VARCHAR2","colCommonUsed":"1","colRelation":"0","attribute":null,"colDic":null,"attributeValue":null,"coldicValue":null,"checked":true,"colControl":null,"nodeId":"1"},{"id":"482605912E93B211CDB8D33C99B78342","sourceId":"83DAC98D2E93B211B6B9511F593E883A","enname":"PARAGRAPHNAME","cnname":"标段名称","pid":"FA7E02912E93B211B88B5EC6EF019138","type":"column","comments":"标段名称","colType":"VARCHAR2","colCommonUsed":"1","colRelation":"0","attribute":null,"colDic":null,"attributeValue":null,"coldicValue":null,"checked":true,"colControl":null,"nodeId":"1"},{"id":"7CA305912E93B21169B4F430FECAE13D","sourceId":"83DAC98D2E93B211B6B9511F593E883A","enname":"PARAGRAPHID","cnname":"标段编号","pid":"FA7E02912E93B211B88B5EC6EF019138","type":"column","comments":"标段编号","colType":"VARCHAR2","colCommonUsed":"1","colRelation":"0","attribute":null,"colDic":null,"attributeValue":null,"coldicValue":null,"checked":true,"colControl":null,"nodeId":"1"},{"id":"AE1D06912E93B211F39DC2E61B7ABA24","sourceId":"83DAC98D2E93B211B6B9511F593E883A","enname":"MEETINGNAME","cnname":"会议名称","pid":"FA7E02912E93B211B88B5EC6EF019138","type":"column","comments":"会议名称","colType":"VARCHAR2","colCommonUsed":"1","colRelation":"0","attribute":null,"colDic":null,"attributeValue":null,"coldicValue":null,"checked":true,"colControl":null,"nodeId":"1"},{"id":"719806912E93B2112799E89A55E6F27A","sourceId":"83DAC98D2E93B211B6B9511F593E883A","enname":"MEETINGTIME","cnname":"会议时间","pid":"FA7E02912E93B211B88B5EC6EF019138","type":"column","comments":"会议时间","colType":"VARCHAR2","colCommonUsed":"1","colRelation":"0","attribute":null,"colDic":null,"attributeValue":null,"coldicValue":null,"checked":true,"colControl":null,"nodeId":"1"},{"id":"110E07912E93B211EC8896A95EC56D74","sourceId":"83DAC98D2E93B211B6B9511F593E883A","enname":"MEETINGLOCATION","cnname":"会议地点","pid":"FA7E02912E93B211B88B5EC6EF019138","type":"column","comments":"会议地点","colType":"VARCHAR2","colCommonUsed":"1","colRelation":"0","attribute":null,"colDic":null,"attributeValue":null,"coldicValue":null,"checked":true,"colControl":null,"nodeId":"1"},{"id":"098207912E93B21189A312659F371776","sourceId":"83DAC98D2E93B211B6B9511F593E883A","enname":"MEETINGPERSIONNUM","cnname":"会议人数","pid":"FA7E02912E93B211B88B5EC6EF019138","type":"column","comments":"会议人数","colType":"NUMBER","colCommonUsed":"1","colRelation":"0","attribute":null,"colDic":null,"attributeValue":null,"coldicValue":null,"checked":true,"colControl":null,"nodeId":"1"},{"id":"0EFB07912E93B211C8BC3098351A4E02","sourceId":"83DAC98D2E93B211B6B9511F593E883A","enname":"REVIEWREPORT","cnname":"评审报告（文件名，另提供附件）","pid":"FA7E02912E93B211B88B5EC6EF019138","type":"column","comments":"评审报告（文件名，另提供附件）","colType":"VARCHAR2","colCommonUsed":"1","colRelation":"0","attribute":null,"colDic":null,"attributeValue":null,"coldicValue":null,"checked":true,"colControl":null,"nodeId":"1"},{"id":"B76908912E93B2117380A4DE90822874","sourceId":"83DAC98D2E93B211B6B9511F593E883A","enname":"METTING_TYPE","cnname":"会议类型","pid":"FA7E02912E93B211B88B5EC6EF019138","type":"column","comments":"会议类型","colType":"VARCHAR2","colCommonUsed":"1","colRelation":"0","attribute":null,"colDic":null,"attributeValue":null,"coldicValue":null,"checked":true,"colControl":null,"nodeId":"1"},{"id":"46FA08912E93B2117AB6A3E9E4916C18","sourceId":"83DAC98D2E93B211B6B9511F593E883A","enname":"REVIEWCONTENT","cnname":"REVIEWCONTENT","pid":"FA7E02912E93B211B88B5EC6EF019138","type":"column","comments":"","colType":"VARCHAR2","colCommonUsed":"1","colRelation":"0","attribute":null,"colDic":null,"attributeValue":null,"coldicValue":null,"checked":true,"colControl":null,"nodeId":"1"}]},"position":{"x":268,"y":253},"group":"nodes","removed":false,"selected":false,"selectable":true,"locked":false,"grabbable":true,"pannable":false,"classes":"T01 eh-preview-active"},{"data":{"id":"2","type":"unbundled-bezier(multiple)","nodeType":"A42","up":["1"],"down":[],"name":"结果存储","columns":[{"id":"312004912E93B21127BB4EA17A44C407","sourceId":"83DAC98D2E93B211B6B9511F593E883A","enname":"PROJECTNAME","cnname":"项目名称","pid":"FA7E02912E93B211B88B5EC6EF019138","type":"column","comments":"项目名称","colType":"VARCHAR2","colCommonUsed":"1","colRelation":"0","attribute":null,"colDic":null,"attributeValue":null,"coldicValue":null,"checked":true,"colControl":null,"nodeId":"1"},{"id":"C5A304912E93B2117CAA5B4CF5E46014","sourceId":"83DAC98D2E93B211B6B9511F593E883A","enname":"PROJECTCODE","cnname":"项目编号","pid":"FA7E02912E93B211B88B5EC6EF019138","type":"column","comments":"项目编号","colType":"VARCHAR2","colCommonUsed":"1","colRelation":"0","attribute":null,"colDic":null,"attributeValue":null,"coldicValue":null,"checked":true,"colControl":null,"nodeId":"1"},{"id":"482605912E93B211CDB8D33C99B78342","sourceId":"83DAC98D2E93B211B6B9511F593E883A","enname":"PARAGRAPHNAME","cnname":"标段名称","pid":"FA7E02912E93B211B88B5EC6EF019138","type":"column","comments":"标段名称","colType":"VARCHAR2","colCommonUsed":"1","colRelation":"0","attribute":null,"colDic":null,"attributeValue":null,"coldicValue":null,"checked":true,"colControl":null,"nodeId":"1"},{"id":"7CA305912E93B21169B4F430FECAE13D","sourceId":"83DAC98D2E93B211B6B9511F593E883A","enname":"PARAGRAPHID","cnname":"标段编号","pid":"FA7E02912E93B211B88B5EC6EF019138","type":"column","comments":"标段编号","colType":"VARCHAR2","colCommonUsed":"1","colRelation":"0","attribute":null,"colDic":null,"attributeValue":null,"coldicValue":null,"checked":true,"colControl":null,"nodeId":"1"},{"id":"AE1D06912E93B211F39DC2E61B7ABA24","sourceId":"83DAC98D2E93B211B6B9511F593E883A","enname":"MEETINGNAME","cnname":"会议名称","pid":"FA7E02912E93B211B88B5EC6EF019138","type":"column","comments":"会议名称","colType":"VARCHAR2","colCommonUsed":"1","colRelation":"0","attribute":null,"colDic":null,"attributeValue":null,"coldicValue":null,"checked":true,"colControl":null,"nodeId":"1"},{"id":"719806912E93B2112799E89A55E6F27A","sourceId":"83DAC98D2E93B211B6B9511F593E883A","enname":"MEETINGTIME","cnname":"会议时间","pid":"FA7E02912E93B211B88B5EC6EF019138","type":"column","comments":"会议时间","colType":"VARCHAR2","colCommonUsed":"1","colRelation":"0","attribute":null,"colDic":null,"attributeValue":null,"coldicValue":null,"checked":true,"colControl":null,"nodeId":"1"},{"id":"110E07912E93B211EC8896A95EC56D74","sourceId":"83DAC98D2E93B211B6B9511F593E883A","enname":"MEETINGLOCATION","cnname":"会议地点","pid":"FA7E02912E93B211B88B5EC6EF019138","type":"column","comments":"会议地点","colType":"VARCHAR2","colCommonUsed":"1","colRelation":"0","attribute":null,"colDic":null,"attributeValue":null,"coldicValue":null,"checked":true,"colControl":null,"nodeId":"1"},{"id":"098207912E93B21189A312659F371776","sourceId":"83DAC98D2E93B211B6B9511F593E883A","enname":"MEETINGPERSIONNUM","cnname":"会议人数","pid":"FA7E02912E93B211B88B5EC6EF019138","type":"column","comments":"会议人数","colType":"NUMBER","colCommonUsed":"1","colRelation":"0","attribute":null,"colDic":null,"attributeValue":null,"coldicValue":null,"checked":true,"colControl":null,"nodeId":"1"},{"id":"0EFB07912E93B211C8BC3098351A4E02","sourceId":"83DAC98D2E93B211B6B9511F593E883A","enname":"REVIEWREPORT","cnname":"评审报告（文件名，另提供附件）","pid":"FA7E02912E93B211B88B5EC6EF019138","type":"column","comments":"评审报告（文件名，另提供附件）","colType":"VARCHAR2","colCommonUsed":"1","colRelation":"0","attribute":null,"colDic":null,"attributeValue":null,"coldicValue":null,"checked":true,"colControl":null,"nodeId":"1"},{"id":"B76908912E93B2117380A4DE90822874","sourceId":"83DAC98D2E93B211B6B9511F593E883A","enname":"METTING_TYPE","cnname":"会议类型","pid":"FA7E02912E93B211B88B5EC6EF019138","type":"column","comments":"会议类型","colType":"VARCHAR2","colCommonUsed":"1","colRelation":"0","attribute":null,"colDic":null,"attributeValue":null,"coldicValue":null,"checked":true,"colControl":null,"nodeId":"1"},{"id":"46FA08912E93B2117AB6A3E9E4916C18","sourceId":"83DAC98D2E93B211B6B9511F593E883A","enname":"REVIEWCONTENT","cnname":"REVIEWCONTENT","pid":"FA7E02912E93B211B88B5EC6EF019138","type":"column","comments":"","colType":"VARCHAR2","colCommonUsed":"1","colRelation":"0","attribute":null,"colDic":null,"attributeValue":null,"coldicValue":null,"checked":true,"colControl":null,"nodeId":"1"}]},"position":{"x":502,"y":237},"group":"nodes","removed":false,"selected":false,"selectable":true,"locked":false,"grabbable":true,"pannable":false,"classes":"abc A42 eh-preview-active"}],"edges":[{"data":{"source":"1","target":"2","id":"7c013a4a-7177-4430-8efa-0f1a417a8d48"},"position":{"x":0,"y":0},"group":"edges","removed":false,"selected":false,"selectable":true,"locked":false,"grabbable":true,"pannable":true,"classes":"eh-preview multi-unbundled-bezier-1"}]}
        put("61FE6CD23093B2111BBC63261B804E3A", CollectionUtil.newArrayList("PROJECTNAME", "t18_NAME", "g6_1"));
    }};

    //查询表中是否包含字段
    private boolean checkFieldExists(Connection conn, String tableName, String fieldName) throws SQLException {
        String sql = "SELECT COUNT(1) FROM USER_TAB_COLUMNS WHERE TABLE_NAME = ? AND COLUMN_NAME = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, tableName.toUpperCase());
            pstmt.setString(2, fieldName.toUpperCase());
            ResultSet rs = pstmt.executeQuery();
            return rs.next() && rs.getInt(1) > 0;
        }
    }
}
